package org.vector.pefind.elfinder.executor;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.json.JSONObject;
import org.vector.pefind.elfinder.iexecutor.CommandExecutor;
import org.vector.pefind.elfinder.iservice.FsService;
import org.vector.pefind.elfinder.model.FsItemEx;

/**
 * This returns the dimensions on an image.
 */
public class DimCommandExecutor extends AbstractJsonCommandExecutor implements
		CommandExecutor {
	
	protected void execute(FsService fsService, HttpServletRequest request,
			ServletContext servletContext, JSONObject json) throws Exception {
		String target = request.getParameter("target");
		FsItemEx item = findItem(fsService, target);
		// If it's not an image then just return empty JSON.
		if (item.getMimeType().startsWith("image")) {
			InputStream inputStream = null;
			try {
				inputStream = item.openInputStream();
				BufferedImage image = ImageIO.read(inputStream);
				int width = image.getWidth();
				int height = image.getHeight();
				json.put("dim", String.format("%dx%d", width, height));
			} catch (IOException ioe) {
				String message = "Failed load image to get dimensions: "
						+ item.getPath();
				if (LOG.isDebugEnabled()) {
					LOG.debug(message, ioe);
				} else {
					LOG.warn(message);
				}

			} finally {
				if (inputStream != null) {
					try {
						inputStream.close();
					} catch (IOException ioe) {
						LOG.debug(
								"Failed to close stream to: " + item.getPath(),
								ioe);
					}
				}
			}

		} else {
			LOG.debug("dim command called on non-image: " + item.getPath());
		}
	}
}
